<template>
  <div class="app-container">
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="表名称" prop="tableName">
        <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input v-model="queryParams.tableComment" placeholder="请输入表描述" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!--<el-button v-hasPermission="['tool:gen:code']" type="primary" icon="el-icon-download" size="mini" @click="handleGenCode">生成</el-button>-->
        <el-button type="primary" icon="el-icon-download" size="mini" @click="handleGenCode">生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <!--<el-button v-hasPermission="['tool:gen:import']" type="info" icon="el-icon-upload" size="mini" @click="openImportDbTable">导入</el-button>-->
        <el-button type="info" icon="el-icon-upload" size="mini" @click="openImportDbTable">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <!--<el-button v-hasPermission="['tool:gen:update']" type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>-->
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <!--<el-button v-hasPermission="['tool:gen:delete']" type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>-->
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <el-table v-loading="loading" :data="page.records" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{ (page.current - 1) * page.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="表名称" align="center" prop="tableName" show-overflow-tooltip width="130" />
      <el-table-column label="表描述" valign="center" prop="tableComment" show-overflow-tooltip width="130" />
      <el-table-column label="实体" align="center" prop="className" show-overflow-tooltip width="130" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button v-hasPermission="['tool:gen:preview']" type="text" size="small" icon="el-icon-view" @click="handlePreview(scope.row)">预览</el-button>
          <el-button v-hasPermission="['tool:gen:update']" type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-hasPermission="['tool:gen:delete']" type="text" size="small" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
          <el-button v-hasPermission="['tool:gen:update']" type="text" size="small" icon="el-icon-refresh" @click="handleSyncDbTable(scope.row)">同步</el-button>
          <el-button v-hasPermission="['tool:gen:code']" type="text" size="small" icon="el-icon-download" @click="handleGenCode(scope.row)">生成</el-button>-->
          <el-button type="text" size="small" icon="el-icon-view" @click="handlePreview(scope.row)">预览</el-button>
          <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
          <el-button type="text" size="small" icon="el-icon-refresh" @click="handleSyncDbTable(scope.row)">同步</el-button>
          <el-button type="text" size="small" icon="el-icon-download" @click="handleGenCode(scope.row)">生成</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />
    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body>
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :key="key"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
        >
          <pre>{{ value }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-db-table ref="importDbTable" @ok="handleQuery" />
  </div>
</template>

<script>
import GenTableApi from '@/api/tool/GenTableApi'
import ImportDbTable from './components/ImportDbTable'
import ZipUtils from '@/utils/ZipUtils'

export default {
  name: 'Gen',
  components: {
    ImportDbTable
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 唯一标识符
      uniqueId: '',
      multipleSelection: [],
      // 选中表数组
      tableNames: [],
      // 非单个禁用
      isSingle: true,
      // 非多个禁用
      isMultiple: true,
      // 显示搜索条件
      searchVisible: true,
      // 日期范围
      dateRange: '',
      // 查询参数
      queryParams: {
        tableName: undefined,
        tableComment: undefined
      },
      page: {
        current: 1,
        pageSize: 100,
        total: 0,
        records: []
      },
      // 预览参数
      preview: {
        open: false,
        title: '代码预览',
        data: {},
        activeName: 'Entity.java'
      }
    }
  },
  created() {
    this.handleQuery()
  },
  activated() {
    const time = this.$route.query.t
    if (time !== null && time !== this.uniqueId) {
      this.uniqueId = time
      this.resetQuery()
    }
  },
  methods: {
    /**
     * 删除
     * @param row
     */
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return GenTableApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    /**
     * 编辑
     * @param row
     */
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.$router.push('/genTable/form/' + id)
    },
    /**
     * 查询
     */
    handleQuery() {
      this.loading = true
      this.page.current = 1
      GenTableApi.page(this.$common.addDateRange(this.queryParams, this.dateRange), this.page).then(response => {
        this.page.records = response.data.records
        this.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    /**
     * 重置查询参数
     */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /**
     * 多选框选中数据
     * @param selection
     */
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.tableNames = selection.map(item => item.tableName)
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    /**
     * 打开导入数据库表弹窗
     */
    openImportDbTable() {
      this.$refs.importDbTable.show()
    },
    /**
     * 预览生成代码
     * @param row
     */
    handlePreview(row) {
      GenTableApi.preview(row.id).then(response => {
        this.preview.data = response.data
        console.log(this.preview.data)
        this.preview.open = true
      })
    },
    /**
     * 同步数据库表结构
     * @param row
     */
    handleSyncDbTable(row) {
      const tableName = row.tableName
      this.$confirm('确认要强制同步"' + tableName + '"表结构吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return GenTableApi.syncDbTable(tableName)
      }).then(() => {
        this.$message.success('同步成功')
      })
    },
    /**
     * 生成代码
     * @param row
     */
    handleGenCode(row) {
      const tableNames = row.tableName || this.tableNames
      if (!tableNames || tableNames.length === 0) {
        this.$message.warning('请选择要生成的数据')
        return
      }
      if (row.genType === '1') {
        GenTableApi.genCode(row.tableName).then(response => {
          this.$message.success('成功生成到自定义路径：' + row.genPath)
        })
      } else {
        ZipUtils.downLoadZip(`/gen/genTable/batchDownload/${tableNames}`, 'liuen')
      }
    }
  }
}
</script>
